﻿using Dapper;
using MKAdminCore.DTO.Web.BasicSetting;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.IService.Web.BasicSetting;
using MKAdminCore.Service.Web.Common;
using MKAdminCore.ToolKit.Encrypt;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MKAdminCore.Service.Web.BasicSetting
{
    public class UserInfoService : IUserInfoService
    {
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public PagingList<GetUserInfo> List(GetUserInfoListParameter parameter)
        {
            var list = new PagingList<GetUserInfo>();

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(@"select OperatorId,OperatorNo,OperatorName,StatusCode
	                                ,CONVERT(varchar(16), CreateTime, 120) CreateTime 
                                from dbo.OperatorInfo oi with(nolock) 
                                Where oi.StatusCode In(0,1) and OperatorNo not in('admin','test')");

                var param = new DynamicParameters();
                if (!string.IsNullOrEmpty(parameter.OperatorName))
                {
                    sql.AppendLine("And oi.OperatorName Like '%'+@OperatorName+'%'");
                    param.Add("@OperatorName", parameter.OperatorName);
                }

                string sortingSql = "Order By OperatorId Desc";
                if (!string.IsNullOrEmpty(parameter.sortName) && !string.IsNullOrEmpty(parameter.sortOrder))
                {
                    sortingSql = $"Order By {parameter.sortName} {parameter.sortOrder}";
                }

                list = conn.QueryGetList<GetUserInfo>(sql.ToString(), sortingSql, parameter.pageIndex, parameter.pageSize, param);

                return list;
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> Add(UserInfoAdd parameter, UserInfo userInfo)
        {
            var result = new HttpResponseResult() { Msg = "新增成功" };

            parameter.OperatorPwd = MD5EncryptHelper.Encrypt(parameter.OperatorPwd);
            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(@"
                                If Not Exists(Select 1 From dbo.OperatorInfo with(nolock) 
                                                Where OperatorNo = @OperatorNo And StatusCode in(0,1))
                                Begin
                                    INSERT INTO [dbo].[OperatorInfo]
                                           ([OperatorNo],[OperatorName],[OperatorPwd],[StatusCode]
                                             ,[Remark],[CreateTime],[UpdateTime])
                                     VALUES
                                           (@OperatorNo,@OperatorName,@OperatorPwd,0
                                             ,'',getdate(),getdate())
                                     Select SCOPE_IDENTITY();
                                End
                                Else
                                Begin
                                    Select -1;
                                End
                                ");

                var param = new DynamicParameters();
                param.Add("@OperatorNo", parameter.OperatorNo);
                param.Add("@OperatorName", parameter.OperatorName);
                param.Add("@OperatorPwd", parameter.OperatorPwd);

                object _r = await conn.ExecuteScalarAsync(sql.ToString(), param);
                if (_r != null)
                {
                    int rOperatorId = Convert.ToInt32(_r);
                    if (rOperatorId == -1)
                    {
                        result.Code = (int)HttpResponseCode.OperateFail;
                        result.Msg = "登录账号已存在";
                    }
                }
                else
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = "新增失败";
                }
                return result;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> Edit(UserInfoEdit parameter)
        {
            var result = new HttpResponseResult() { Msg = "修改成功" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine(@"Update [dbo].[OperatorInfo]
                                 Set [OperatorName] = @OperatorName
                                     ,[UpdateTime] = getdate()
                                 Where OperatorId = @OperatorId");

                var param = new DynamicParameters();
                param.Add("@OperatorId", parameter.OperatorId);
                param.Add("@OperatorNo", parameter.OperatorNo);
                param.Add("@OperatorName", parameter.OperatorName);

                int _r = await conn.ExecuteAsync(sql.ToString(), param);
                if (_r <= 0)
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = "修改失败";
                }
                return result;
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> ResetPwd(UserInfoResetPassword parameter)
        {
            var result = new HttpResponseResult() { Msg = "重置密码成功" };

            parameter.OperatorPwd = MD5EncryptHelper.Encrypt(parameter.OperatorPwd);
            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"Update [dbo].[OperatorInfo]
                                  Set OperatorPwd = @OperatorPwd ,UpdateTime = GetDate()
                                  Where OperatorId = {parameter.OperatorId}");

                var param = new DynamicParameters();
                param.Add("@OperatorId", parameter.OperatorId);
                param.Add("@OperatorPwd", parameter.OperatorPwd);

                int _r = await conn.ExecuteAsync(sql.ToString(), param);
                if (_r <= 0)
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = "重置密码失败";
                }
                return result;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> Del(UserInfoDel parameter)
        {
            var result = new HttpResponseResult() { Msg = "删除成功" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"Update [dbo].[OperatorInfo]
                                  Set StatusCode = 2 ,UpdateTime = GetDate()
                                  Where OperatorId = {parameter.OperatorId}");

                int _r = await conn.ExecuteAsync(sql.ToString());
                if (_r <= 0)
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = "删除失败";
                }
                return result;
            }
        }

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> UpdateStatus(UserInfoUpdateStatus parameter)
        {
            var result = new HttpResponseResult() { Msg = parameter.StatusCode == 0 ? "启用成功" : "禁用成功" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"Update [dbo].[OperatorInfo]
                                  Set StatusCode = {parameter.StatusCode} ,UpdateTime = GetDate()
                                  Where OperatorId = {parameter.OperatorId}");

                int _r = await conn.ExecuteAsync(sql.ToString());
                if (_r <= 0)
                {
                    result.Code = (int)HttpResponseCode.OperateFail;
                    result.Msg = parameter.StatusCode == 0 ? "启用失败" : "禁用失败";
                }
                return result;
            }
        }

        /// <summary>
        /// 获取用户角色
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> GetRoleInfo(UserInfoGetRoleInfo parameter)
        {
            var result = new HttpResponseResult<List<OperatorAllotRoleInfo>>() { Msg = "" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"  select t1.RoleId,t1.RoleName,
	                                    case 
		                                    when t2.OperatorId > 0 then 1
		                                    else 0 end Checked from dbo.OperatorRoleInfo t1 with(nolock)
                                    left join dbo.OperatorRoleConfig t2 with(nolock)
                                    on t1.RoleId = t2.RoleId and t2.OperatorId = {parameter.OperatorId}
                                    where t1.StatusCode = 0");

                var _r = await conn.QueryAsync<OperatorAllotRoleInfo>(sql.ToString());

                result.Data = _r.ToList();
                return result;
            }
        }

        /// <summary>
        /// 分配角色
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> AllotRole(AllotRoleInfo parameter)
        {
            var result = new HttpResponseResult() { Msg = "分配角色成功" };

            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"Delete From [dbo].[OperatorRoleConfig] 
                                    Where OperatorId = {parameter.OperatorId}");

                await conn.ExecuteAsync(sql.ToString());

                if (parameter.RoleIds != null && parameter.RoleIds.Count > 0)
                {
                    var allotRoleInfoConfig = new List<AllotRoleInfoConfig>();
                    parameter.RoleIds.ForEach((q) =>
                    {
                        allotRoleInfoConfig.Add(new AllotRoleInfoConfig()
                        {
                            OperatorId = parameter.OperatorId,
                            RoleId = q,
                            UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        });
                    });

                    StringBuilder sqlAllotRoleInfoConfig = new StringBuilder();
                    sqlAllotRoleInfoConfig.AppendLine($@"
                                    insert into dbo.OperatorRoleConfig(OperatorId,RoleId,UpdateTime)
                                    values(@OperatorId,@RoleId,@UpdateTime)");
                    await conn.ExecuteAsync(sqlAllotRoleInfoConfig.ToString(), allotRoleInfoConfig);
                }
                return result;
            }
        }
    }
}
